#include "logmanager.h"
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QDir>

LogManager::LogManager(QTextEdit *logWidget, QObject *parent)
    : QObject(parent)
    , logWidget_(logWidget)
{
}

void LogManager::addLog(const QString &message)
{
    logWidget_->append(message);
    logWidget_->moveCursor(QTextCursor::End);
}

void LogManager::clearLog()
{
    logWidget_->clear();
}

void LogManager::exportLog()
{
    QString logText = logWidget_->toPlainText();
    if (logText.isEmpty()) {
        QMessageBox::information(nullptr, "提示", "没有可导出的日志");
        return;
    }

    QString fileName = QFileDialog::getSaveFileName(nullptr,
                                                    "导出日志",
                                                    QDir::homePath() + "/modbus_log.txt",
                                                    "文本文件 (*.txt)");
    if (fileName.isEmpty()) {
        QMessageBox::information(nullptr, "提示", "导出已取消");
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::information(nullptr, "提示", "无法打开文件保存日志");
        return;
    }

    QTextStream out(&file);
    out << logText;
    file.close();

    QMessageBox::information(nullptr, "提示", "日志已成功导出到: " + fileName);
}
